package com.edais.actions;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Serializable;
import java.io.UnsupportedEncodingException;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.edais.util.FtpUtil;

/**
 * @author taozun 2014-11-13 上午11:52:10 活动相关action
 */
@Controller
@RequestMapping("/test")

public class TestServerAction  implements Serializable {
	private static final Log logger = LogFactory.getLog(TestServerAction.class);

	/**
	 * 
	 * @param imageFile
	 * @return
	 * @throws IOException 
	 */
	@ResponseBody
	@RequestMapping(value = "/upload")
	public String updateImg(HttpServletRequest request,
			HttpServletResponse response
			//,@RequestParam("imageFile") MultipartFile imageFile
			) throws IOException {
		System.out.println("开始接收文件");
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request; 
        List<MultipartFile> list = (List<MultipartFile>)multipartRequest.getFiles("img");
       
        if(null==list||0==list.size()){
        	System.out.println("没有上传文件");
        }
        MultipartFile imageFile = (MultipartFile)list.get(0);
        InputStream inputStream = null;
        FtpUtil fu = null;
	    if(!imageFile.isEmpty()) {
	        try {
	        	
	        	int length = imageFile.getBytes().length;
	        	System.out.println(length);
	            //1.传入输入流(成功)
	             fu = new FtpUtil();
	            inputStream = imageFile.getInputStream();
	            fu.uploadFileInputStream("head.jpg",inputStream);
	            
	            
	        	//System.out.println(imageFile.getOriginalFilename());
	        	//byte[] bytes = imageFile.getBytes();
	        	//int length1 = imageFile.getBytes().length;
	        	//System.out.println(length1);
	        	//System.out.println(imageFile.getContentType());
	        	//System.out.println(imageFile.getName());
	        	//System.out.println(imageFile.getInputStream());
	        	//imageFile.transferTo(new File("D://temp//" + imageFile.getOriginalFilename()));
	        	
	        	System.out.println("接收文件成功。。。");
	            return "success";
	        } catch (IllegalStateException e) {
	            e.printStackTrace();
	        } catch (IOException e) {
	            e.printStackTrace();
	        }finally{
	        	inputStream.close();
	        	
	        }
	    }
	    return "failure";
	}
	    
	@RequestMapping(value = "/getTest")
	public void uploadFile(HttpServletRequest request,
			HttpServletResponse response) {
		try {
			request.setCharacterEncoding("utf-8");
		} catch (UnsupportedEncodingException e1) {
			e1.printStackTrace();
		}
		// 获得磁盘文件条目工厂。
		DiskFileItemFactory factory = new DiskFileItemFactory();
		// 获取文件上传需要保存的路径，upload文件夹需存在。
		String path = request.getSession().getServletContext()
				.getRealPath("/upload/");
		// 设置暂时存放文件的存储室，这个存储室可以和最终存储文件的文件夹不同。因为当文件很大的话会占用过多内存所以设置存储室。
		factory.setRepository(new File(path));
		// 设置缓存的大小，当上传文件的容量超过缓存时，就放到暂时存储室。
		factory.setSizeThreshold(1024 * 1024);
		// 上传处理工具类（高水平API上传处理？）
		ServletFileUpload upload = new ServletFileUpload(factory);

		try {
			// 调用 parseRequest（request）方法 获得上传文件 FileItem 的集合list 可实现多文件上传。
			Boolean flg = upload.isMultipartContent(request);
			System.out.println(flg);
			//springmvc
			//MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request; 
		    //MultipartFile file = multipartRequest.getFile("imgFile");
		    //String fileName = file.getOriginalFilename();
			//MultiPartRequestWrapper wrapper = (MultiPartRequestWrapper) request;//struts2处理
			
			List<FileItem> fileItems = (List<FileItem>) upload.parseRequest(request);
			for (FileItem item : fileItems) {
				// 获取表单属性名字。
				String name = item.getFieldName();
				// 如果获取的表单信息是普通的文本信息。即通过页面表单形式传递来的字符串。
				if (item.isFormField()) {
					// 获取用户具体输入的字符串，
					String value = item.getString();
					request.setAttribute(name, value);
				}
				// 如果传入的是非简单字符串，而是图片，音频，视频等二进制文件。
				else {
					// 获取路径名
					String value = item.getName();
					// 取到最后一个反斜杠。
					int start = value.lastIndexOf("\\");
					// 截取上传文件的 字符串名字。+1是去掉反斜杠。
					String filename = value.substring(start + 1);
					request.setAttribute(name, filename);

					/*
					 * 第三方提供的方法直接写到文件中。 item.write(new File(path,filename));
					 */
					// 收到写到接收的文件中。
					OutputStream out = new FileOutputStream(new File(path,
							filename));
					InputStream in = item.getInputStream();

					int length = 0;
					byte[] buf = new byte[1024];
					System.out.println("获取文件总量的容量:" + item.getSize());

					while ((length = in.read(buf)) != -1) {
						out.write(buf, 0, length);
					}
					in.close();
					out.close();
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	
		
		
	}
}
